import random

from django.shortcuts import render
from django import forms
from django.contrib.auth import authenticate
from django.forms import fields
from django.contrib.auth import login,logout
from django.shortcuts import redirect
from django.http import JsonResponse,HttpResponseRedirect,HttpResponse
from django.contrib import messages
#from .models import *
from datetime import datetime
from django.core.exceptions import ValidationError

# Create your views here.
class LoginForm(forms.Form):
    username = fields.CharField(
        required=True,
        min_length=2,
        max_length=18,
        error_messages={
            "required":"用户名不存在！！",
            "min_length":"用户名不能低于2位！！",
            "max_length":"用户名不能超过18位！！"
        }
    )
    password = fields.CharField(
        required=True,
        error_messages={
            "required":"密码不为空！！"
        }
    )

def login_user(request):
    if request.method=="GET":
        return render(request,'login.html')
    if request.method=="POST":
        form =LoginForm(request.POST)
        if form.is_valid():
            username=form.cleaned_data.get("username")
            password=form.cleaned_data.get("password")
            user=authenticate(username=username,password=password)
            if user:
                login(request,user)
                request.session.set_expiry(None)
                return redirect('/front_index')
            else:
                messages.error(request,'用户名不存在或密码错误！！')
                return HttpResponseRedirect('/login/')

class RegisterForm(forms.Form):
    username=fields.CharField(
        required=True,
        min_length=2,
        max_length=18,
        error_messages={
            "required": "用户名不为空！！",
            "min_length": "用户名不能低于2位！！",
            "max_length": "用户名不能超过18位！！"
        }
    )
    password1 =fields.CharField(
        required=True,
        min_length=6,
        max_length=18,
        error_messages={
            "required": "密码不为空！！",
            "min_length": "密码不能低于6位！！",
            "max_length": "密码不能超过18位！！"
        }
    )
    password2 = fields.CharField(required=False)
    email=fields.EmailField(
        required=True,
        error_messages={
            "required": "邮箱不为空！！",
        }
        )
    def clean_password2(self):
        if not self.errors.get("password1"):
            if self.cleaned_data["password2"]!=self.cleaned_data["password1"]:
                raise ValidationError("两次密码不一致")

def register(request):
    if request.method=="GET":
        return render(request,"register.html")
    if request.method=="POST":
        form = RegisterForm(request,"register.html")
        if form.is_valid():
            username=form.cleaned_data["username"]
            password=form.cleaned_data["password1"]
            email=form.cleaned_data["email"]
            username_exists=UserInfo.objects.filter(username=username).exists()
            if username_exists:
                messages.error(request,'该用户名已存在！')
                return HttpResponseRedirect('/register/')
            email_exists=UserInfo.objects.filter(email=email).exists()
            if email_exists:
                messages.error(request,'该邮箱已注册过！')
                return HttpResponseRedirect('/register/')
            user_ID=datetime.now().strftime("%Y%m%d%H%M%S")+str(random.randint(1000,9999))
            UserInfo.objects.create_user(username=username,password=password,email=email,user_ID=user_ID)
            messages.success(request,"注册成功，请登录")
            return HttpResponseRedirect('/login/')
        else:
            return HttpResponseRedirect('/register/')


def logout_user(request):
    logout(request)
    return redirect('/front_index/')















def register():
    return None


def login_user():
    return None


def logout_user():
    return None